/**
 * 角色管理控制器 - 处理RBAC角色的创建、查询、管理等REST API接口
 *
 * 开发人员：马勇俐
 * 开发时间：2025-11-16 至 2025-11-20
 * 模块职责：提供RBAC角色相关的REST API接口，支持角色的创建、查询、更新、删除等完整权限管理功能
 *
 * 技术要点：
 * - RESTful API设计，遵循REST规范
 * - 多租户架构，企业级数据隔离
 * - AOP审计日志记录操作轨迹
 * - 角色权限管理和继承机制
 * - 参数验证和异常处理机制
 *
 * 开发故事：负责角色管理控制器的开发，与角色服务层和前端权限界面深度配合，确保RBAC权限系统的完整性和安全性。
 */
package com.pbl.controller;

import com.pbl.aspect.AuditLog;
import com.pbl.common.model.ApiResponse;
import com.pbl.dto.RoleDto;
import com.pbl.entity.Role;
import com.pbl.service.RoleService;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/enterprises/{enterpriseId}/roles")
public class RoleController {

    private final RoleService roleService;

    /**
     * 构造角色控制器
     * @param roleService 角色服务层
     */
    public RoleController(RoleService roleService) {
        this.roleService = roleService;
    }

    @AuditLog(action = "role.create", resource = "role")
    @PostMapping
    public ApiResponse<Role> create(@PathVariable Long enterpriseId, @Valid @RequestBody RoleDto dto) {
        Role r = new Role();
        r.setCode(dto.getCode());
        r.setName(dto.getName());
        r.setDescription(dto.getDescription());
        return ApiResponse.success(roleService.create(enterpriseId, r));
    }

    @AuditLog(action = "role.update", resource = "role")
    @PutMapping("/{id}")
    public ApiResponse<Role> update(@PathVariable Long enterpriseId, @PathVariable Long id, @Valid @RequestBody RoleDto dto) {
        Role r = new Role();
        r.setName(dto.getName());
        r.setDescription(dto.getDescription());
        return ApiResponse.success(roleService.update(id, r));
    }

    @GetMapping("/{id}")
    public ApiResponse<Role> get(@PathVariable Long enterpriseId, @PathVariable Long id) {
        return ApiResponse.success(roleService.get(id));
    }

    @AuditLog(action = "role.delete", resource = "role")
    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long enterpriseId, @PathVariable Long id) {
        roleService.delete(id);
        return ApiResponse.success();
    }

    @GetMapping
    public ApiResponse<List<Role>> list(@PathVariable Long enterpriseId) {
        return ApiResponse.success(roleService.listByEnterprise(enterpriseId));
    }
}
